package com.engine.wei.base.net;

import com.engine.wei.base.utils.log.LogUtils;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava3.RxJava3CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * 作者:赵若位
 * 时间:2021/8/26 13:57
 * 功能:
 */
public class RetrofitManager {

    private OkHttpClient mClient;
    private Retrofit mRetrofit;
    private ApiService mApiService;


    private RetrofitManager() {
        throw new IllegalStateException("You can't instantiate me~");
    }

    /**
     * 单例初始化
     *
     * @return
     */
    public RetrofitManager getManager() {
        return Singleton.RETROFITMANAGER;
    }

    /**
     * 提供OkHttpClient客户端
     *
     * @return
     */
    public OkHttpClient providerClient() {
        if (null == mClient) {
            mClient = new OkHttpClient.Builder()
                    .readTimeout(Singleton.DELAY_TIME, TimeUnit.MILLISECONDS)
                    .connectTimeout(Singleton.DELAY_TIME, TimeUnit.MILLISECONDS)
                    .writeTimeout(Singleton.DELAY_TIME, TimeUnit.MILLISECONDS)
                    .addInterceptor(new HttpLoggingInterceptor(s -> LogUtils.i(s)).setLevel(HttpLoggingInterceptor.Level.BODY))
                    .build();
        }
        return mClient;
    }

    /**
     * 提供Retrofit客户端
     *
     * @return
     */
    public Retrofit providerRetrofit() {
        if (null == mRetrofit) {
            mRetrofit = new Retrofit.Builder()
                    .baseUrl("http://XXX.com")
                    .addConverterFactory(GsonConverterFactory.create())
                    .addCallAdapterFactory(RxJava3CallAdapterFactory.create())
                    .client(providerClient())
                    .build();
        }
        return mRetrofit;
    }

    /**
     * 提供Api接口
     *
     * @return
     */
    public ApiService providerApiService() {
        if (null == mApiService) {
            mApiService = providerRetrofit().create(ApiService.class);
        }
        return mApiService;
    }

    public static class Singleton {
        private static final RetrofitManager RETROFITMANAGER = new RetrofitManager();
        private static final Long DELAY_TIME = 10 * 1000L;
    }
}
